﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Nantianmen.EntityFrameworkCore.Migrations
{
    public class PostgresqlDbContextDesignTimeFactory : IDesignTimeDbContextFactory<NantianmenDbContext>
    {
        public NantianmenDbContext CreateDbContext(string[] args)
        {
            var hostBuilder = Host.CreateApplicationBuilder(args);
            hostBuilder.Configuration.AddJsonFile("appsettings.json");
            hostBuilder.Services.AddDbContext<NantianmenDbContext>(options =>
            {
                options.UseNpgsql(
                    hostBuilder.Configuration.GetConnectionString("Npgsql"),
                    x => x.MigrationsAssembly("Nantianmen.EntityFrameworkCore.Migrations"));
            });

            var host = hostBuilder.Build();
            var dbContext = host.Services.GetRequiredService<NantianmenDbContext>();

            return dbContext;
        }
    }
}
